package com.vk.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.vk.project.model.vo.InterfaceInfoVO;
import com.vk.project.service.UserInterfaceInfoService;
import com.vk.vkapiclientsdk.client.VkApiClient;
import com.vk.project.annotation.AuthCheck;
import com.vk.project.common.*;
import com.vk.project.constant.CommonConstant;
import com.vk.project.exception.BusinessException;
import com.vk.project.model.dto.interfaceinfo.InterfaceInfoAddRequest;
import com.vk.project.model.dto.interfaceinfo.InterfaceInfoInvokeRequest;
import com.vk.project.model.dto.interfaceinfo.InterfaceInfoQueryRequest;
import com.vk.project.model.dto.interfaceinfo.InterfaceInfoUpdateRequest;
import com.vk.vkapicommon.model.entity.InterfaceInfo;
import com.vk.vkapicommon.model.entity.User;
import com.vk.project.model.enums.InterfaceInfoStatusEnum;
import com.vk.project.service.InterfaceInfoService;
import com.vk.project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @ClassName : InterfaceInfoController
 * @Description : 接口管理控制器
 * @Author : LYQ
 * @Date: 2023-12-08 15:23
 */
@Slf4j
@RestController
@RequestMapping("/interfaceInfo")
public class InterfaceInfoController {

    @Autowired
    private UserInterfaceInfoService userInterfaceInfoService;

    @Autowired
    private InterfaceInfoService interfaceInfoService;

    @Autowired
    private UserService userService;

    /**
     * 添加接口信息
     *
     * @param interfaceInfoAddRequest 接口信息添加请求对象
     * @param request                 请求体
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addInterfaceInfo(@RequestBody InterfaceInfoAddRequest interfaceInfoAddRequest, HttpServletRequest request) {
        // 判断请求参数是否为空
        if (interfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 将请求参数复制到InterfaceInfo对象中
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoAddRequest, interfaceInfo);
        // 校验InterfaceInfo对象
        interfaceInfoService.validInterfaceInfo(interfaceInfo, true);
        // 获取登录用户
        User loginUser = userService.getLoginUser(request);
        // 设置用户ID
        interfaceInfo.setUserId(loginUser.getId());
        // 设置接口状态
        interfaceInfo.setStatus(InterfaceInfoStatusEnum.ONLINE.getValue());
        // 保存InterfaceInfo对象
        boolean result = interfaceInfoService.save(interfaceInfo);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        // 获取新保存的InterfaceInfo的ID
        long newInterfaceInfoId = interfaceInfo.getId();
        // 返回结果
        return ResultUtils.success(newInterfaceInfoId);
    }

    /**
     * 删除接口信息
     *
     * @param deleteRequest 删除请求对象
     * @param request       请求体
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteInterfaceInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        // 删除接口信息
        Boolean isDeleted = interfaceInfoService.deleteInterfaceInfo(deleteRequest, request);
        // 返回结果
        return ResultUtils.success(isDeleted);
    }

    /**
     * 更新接口信息
     *
     * @param interfaceInfoUpdateRequest 接口信息更新请求对象
     * @param request                    请求体
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateInterfaceInfo(@RequestBody InterfaceInfoUpdateRequest interfaceInfoUpdateRequest, HttpServletRequest request) {
        // 检查请求参数是否为空
        if (interfaceInfoUpdateRequest == null || interfaceInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 根据id创建一个新的InterfaceInfo实体
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        // 将传入的参数复制到新的实体中
        BeanUtils.copyProperties(interfaceInfoUpdateRequest, interfaceInfo);
        // 参数校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, false);
        // 获取当前登录用户
        User user = userService.getLoginUser(request);
        // 获取传入的id
        long id = interfaceInfoUpdateRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        // 如果不存在，抛出未找到错误
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可修改
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 根据id更新接口信息
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        // 返回更新结果
        return ResultUtils.success(result);
    }

    /**
     * 根据Id获取接口信息
     *
     * @param id 接口的Id
     * @return 返回接口信息
     */
    @GetMapping("/get/{id}")
    public BaseResponse<InterfaceInfo> getInterfaceInfoById(@PathVariable long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        return ResultUtils.success(interfaceInfo);
    }

    /**
     * 获取接口信息列表
     *
     * @param interfaceInfoQueryRequest 查询接口信息列表请求对象
     * @return 返回接口信息列表
     */
    @GetMapping("/list")
    public BaseResponse<List<InterfaceInfo>> listInterfaceInfo(InterfaceInfoQueryRequest interfaceInfoQueryRequest) {
        // 创建接口信息查询对象
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        // 如果传入的参数不为空，则将其复制到接口信息查询对象中
        if (interfaceInfoQueryRequest != null) {
            BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        }
        // 创建查询条件构造器
        LambdaQueryWrapper<InterfaceInfo> queryWrapper = new LambdaQueryWrapper<>(interfaceInfoQuery);
        queryWrapper.eq(InterfaceInfo::getStatus,1);
        // 根据查询条件查询出接口信息列表
        List<InterfaceInfo> interfaceInfoList = interfaceInfoService.list(queryWrapper);
        // 返回接口信息列表
        return ResultUtils.success(interfaceInfoList);
    }

    /**
     * 分页获取接口信息列表
     *
     * @param interfaceInfoQueryRequest 查询接口信息列表请求对象
     * @param request                   请求体
     * @return 返回接口信息列表
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<InterfaceInfoVO>> listInterfaceInfoByPage(@RequestBody InterfaceInfoQueryRequest interfaceInfoQueryRequest, HttpServletRequest request) {
        // 检查请求参数是否为空
        if (interfaceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Page<InterfaceInfoVO> interfaceInfoVOPage = interfaceInfoService.listInterfaceInfoByPage(interfaceInfoQueryRequest, request);
        // 返回查询结果
        return ResultUtils.success(interfaceInfoVOPage);
    }

    /**
     * 发布接口
     *
     * @param interfaceInfoInvokeRequest 接口调用请求对象
     * @param request                    请求体
     * @return
     */
    @PostMapping("/online")
    public BaseResponse<Boolean> onlineInterfaceInfo(@RequestBody InterfaceInfoInvokeRequest interfaceInfoInvokeRequest, HttpServletRequest request) {
        boolean result = interfaceInfoService.onLineInterface(interfaceInfoInvokeRequest, request);
        // 返回一个成功的响应，响应中携带result值
        return ResultUtils.success(result);
    }

    /**
     * 下线接口
     *
     * @param idRequest Id请求对象
     * @param request   请求体
     * @return
     */
    @PostMapping("/offline")
    public BaseResponse<Boolean> offlineInterfaceInfo(@RequestBody IdRequest idRequest, HttpServletRequest request) {
        boolean result = interfaceInfoService.offLineInterface(idRequest, request);
        // 返回一个成功的响应，响应中携带result值
        return ResultUtils.success(result);
    }

    /**
     * 测试调用接口
     *
     * @param interfaceInfoInvokeRequest 接口调用请求对象
     * @param request                    请求体
     * @return
     */
    @PostMapping("/invoke")
    public BaseResponse<Object> invokeInterfaceInfo(@RequestBody InterfaceInfoInvokeRequest interfaceInfoInvokeRequest, HttpServletRequest request) {
        // 检查请求对象是否为空或者接口id是否小于等于0
        if (interfaceInfoInvokeRequest == null || interfaceInfoInvokeRequest.getId() <= 0) {
            // 抛出业务异常，表示参数错误
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取接口id
        Long id = interfaceInfoInvokeRequest.getId();
        // 获取用户请求参数
        String userRequestParams = interfaceInfoInvokeRequest.getUserRequestParams();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 判断用户是否还有次数
        int num = userInterfaceInfoService.getleftNumByUserIdAndInterfaceId(interfaceInfoInvokeRequest.getUserId(), interfaceInfoInvokeRequest.getId());
        if(num <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "剩余调用次数不足！请重新开通接口！");
        }
        // 检查接口状态是否为下线状态
        if (oldInterfaceInfo.getStatus() == InterfaceInfoStatusEnum.OFFLINE.getValue()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口已关闭");
        }
        // 调用服务层接口，获取执行结果
        String invokeResult = interfaceInfoService.getInvokeResult(interfaceInfoInvokeRequest, request ,oldInterfaceInfo);
        // 返回调用结果
        return ResultUtils.success(invokeResult);
    }
}
